package com.lazason.wib4android;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Timer;

import weibo4andriod.Status;
import weibo4andriod.WeiboException;
import weibo4andriod.http.AccessToken;
import weibo4andriod.http.RequestToken;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.LinearLayout.LayoutParams;

import com.lazason.wib4android.PullToRefreshListView.OnRefreshListener;


public class TimelineActivity extends BasicWib {
	private static String tag="TimelineActivity";

	long max_id;
	long since_id;
	long current_id;
	PullToRefreshListView listView;
	boolean needExit=false;
	 
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		layoutResource = android.R.id.list;
		Uri uri = this.getIntent().getData();
		SharedPreferences mySharedPreferences = getSharedPreferences(WIB, mode);
		String token = mySharedPreferences.getString("token", null);
		String tokenSecret = mySharedPreferences.getString("tokenSecret", null);
		
		if (token == null || tokenSecret == null){
			try {
				RequestToken requestToken = OAuthConstant.getInstance()
						.getRequestToken();
				AccessToken accessToken = requestToken.getAccessToken(uri
						.getQueryParameter("oauth_verifier"));
				OAuthConstant.getInstance().setAccessToken(accessToken);
				weibo = OAuthConstant.getInstance().getWeibo();
				weibo.setToken(OAuthConstant.getInstance().getToken(),
						OAuthConstant.getInstance().getTokenSecret());

				SharedPreferences.Editor editor = mySharedPreferences.edit();
				editor.putString("token", accessToken.getToken());
				editor.putString("tokenSecret", accessToken.getTokenSecret());
				editor.putString("style", "nomal");
				editor.commit();
			} catch (WeiboException e) {
				e.printStackTrace();
			}
		}

		
		super.onCreate(savedInstanceState);
		initActivity(savedInstanceState);
		listView = (PullToRefreshListView) findViewById(android.R.id.list);
		
		
		listView.setOnRefreshListener(new OnRefreshListener() {
	            @Override
	            public void onRefresh() {
	                // Do work to refresh the list here.
	            	if(!isRefreshLoading){
	            		isRefreshLoading=true;
	                new TimeLineTask().execute(REFRESH);
	            	}
	            }
	        });
		
		adapter = new MyAdapter(this, data,
				R.layout.listitem, new String[] { "profile", "weibo",
						"username", "picture", "retweetedText",
						"retweetedThumbnailPic","created_at","comment_repost","retweetedUsername" }, new int[] {
						R.id.profile, R.id.weibo, R.id.username,
						R.id.picture, R.id.retweetedText,
						R.id.retweetedThumbnailPic, R.id.createdTime, R.id.comment_repost,R.id.retweetedUser}, listView);

		// List<weibo4andriod.Status> friendsTimeline = null;
	

				if (token != null && tokenSecret != null) {
					weibo = OAuthConstant.getInstance().getWeibo();
					weibo.setToken(token, tokenSecret);
					if(MyApplication.data!=null&&MyApplication.data.size()>0){
						data.addAll(MyApplication.data);
						since_id = (Long)data.get(0).get("weibo_id");
						max_id = (Long)data.get(data.size()-1).get("weibo_id");
						listView.setAdapter(adapter);
						isFirstWeibo=false;
					} else {
						m_ProgressDialog = ProgressDialog.show(this, "Please wait...",
								"loading data ...", true, true);
						// 设置ProgressDialog 是否可以按退回按键取消
						m_ProgressDialog.setCancelable(true);
						needToNotifyDataChanged = true;
						timeLineTask = new TimeLineTask();
						timeLineTask.execute(MORE);
					}
					
				} else { 
					
						timeLineTask = new TimeLineTask();
						timeLineTask.execute(MORE);
				 
				}
				//showPopupWindow();
				Timer timer = new Timer();
				timer.schedule(new initPopupWindow(), 100);
	}

	protected void initActivity(Bundle savedInstanceState) {
		super.initActivity(savedInstanceState,R.layout.pull_to_refresh);
	}

	@Override
	protected List readTimeline(int arg) throws WeiboException {
		// TODO Auto-generated method stub
		if(max_id==0&&since_id==0){
			return weibo.getFriendsTimeline();
		} else if(arg==REFRESH){
			 return weibo.getFriendsTimeline(since_id);
		} else {
			return weibo.getFriendsTimeline(max_id-1,true);
		}
		
	}

	@Override
	protected void addData(List list) {
		// TODO Auto-generated method stub
		ArrayList<Map<String, Object>> newList = new ArrayList<Map<String, Object>>(); 
		boolean isNeedToAddToTop = false;
		for (Object status : list) {
			try{
			if(status instanceof Status){
				Map<String, Object> map = Util.status2Map((Status)status);
				newList.add(map);
				current_id = ((Status)status).getId();
				if(max_id==0&&since_id==0){
					max_id = current_id;
					since_id = current_id;
				} 
				if(current_id>since_id){
					since_id = current_id;
					isNeedToAddToTop = true;
					
				}
				if(current_id<max_id){
					max_id = current_id;
					 
				}
			

			
			
			}
			}catch(Exception e){
				Log.d(this.getClass().getName(), e.toString());
			}
		

		}
		if(isNeedToAddToTop){
			//newList.addAll(data);

			ArrayList<Map<String, Object>> tempList = new ArrayList<Map<String, Object>>(); 
			tempList.addAll(data);
			data.clear();
			data.addAll(newList);
			data.addAll(tempList);
			
			// listView.removeFooterView(progressBar);
			// progressBar.setVisibility(View.INVISIBLE);
			adapter.notifyDataSetChanged();
			
			listView.onRefreshComplete();
			//resetRefreshLoading();
			isRefreshLoading=false;
		} else {
			tempData.addAll(newList);
			if (isFirstWeibo) {
				data.addAll(tempData);
				tempData.clear();
				isFirstWeibo = false;
				listView.setAdapter(adapter);

			}  else {
				if (needToNotifyDataChanged) {
					data.addAll(tempData);
					// listView.removeFooterView(progressBar);
					// progressBar.setVisibility(View.INVISIBLE);
					adapter.notifyDataSetChanged();
					tempData.clear();
				}
			}
			 
			loadingLayout.setVisibility(View.GONE);
			isLoading = false;
		}
		
		
		 
	}

	@Override
	void refresh() {
		// TODO Auto-generated method stub
		if(MyApplication.data!=null){
		MyApplication.data.clear();
		}
		data.clear();
		Intent intent = new Intent(); 
		intent.setClass(this, TimelineActivity.class);
		startActivity(intent);
		this.finish();
	}

	@Override
	public void onLowMemory() {
		// TODO Auto-generated method stub
		super.onLowMemory();
		MyApplication.getInstance().onLowMemory();
		Log.d(tag, "low memory");
		Log.d("onLowMemory", "low memory");
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		//super.onBackPressed();
		if(needExit){
		MyApplication.getInstance().exit();
		}else {
			needExit=true;
			Toast.makeText(this, "再按一次退出", 500).show();  
			resetNeedExit();
		}
	}
    void resetNeedExit(){
    	new Thread(){

			@Override
			public void run() {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					 
				}
				needExit=false;
			}
    		
    	}.start();
    }
}
